package com.meichis.yndms.room;

import android.database.Cursor;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;

import com.meichis.yndms.MCApplication;
import com.meichis.yndms.model.*;
import com.meichis.yndms.room.converter.EntityConverter;
import com.meichis.yndms.room.converter.ListConverter;
import com.meichis.yndms.room.converter.MapConverter;
import com.meichis.yndms.room.dao.*;


@Database(entities = {Picture.class, VisitTemplate.class, OfficialCity.class, VisitWorkItem.class, VisitWork.class, DicDataItem.class},
        version = 2)
@TypeConverters({EntityConverter.class, ListConverter.class, MapConverter.class})
public abstract class AppDatabase extends RoomDatabase {

    private static volatile AppDatabase INSTANCE;

    public abstract VisitTemplateDao visitTemplateDao();

    public abstract PictureDao pictureDao();

    public abstract OfficialCityDao officialCityDao();

    public abstract VisitWorkDao visitWorkDao();

    public abstract VisitWorkItemDao visitWorkItemDao();

    public abstract DicDataItemDao dicDataItemDao();


    public static AppDatabase getInstance() {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(MCApplication.getContext(),
                            AppDatabase.class, "mcs.db")
                            .allowMainThreadQueries()
                            .build();
                }
            }
        }
        return INSTANCE;
    }


    public void execSQL(String sql) {
        beginTransaction();
        try {
            getOpenHelper().getWritableDatabase().execSQL(sql);
            setTransactionSuccessful();
        } finally {
            this.endTransaction();
            close();
        }
    }

    /**
     * 不建议使用
     *
     * @param sql
     * @return
     */
    public Cursor query(String sql) {
        beginTransaction();
        Cursor cursor;
        try {
            cursor = getOpenHelper().getWritableDatabase().query(sql);
            setTransactionSuccessful();
        } finally {
            this.endTransaction();
        }
        return cursor;
    }

}
